using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Page
{
    [Serializable()]
    public class PageHits : Csla.BusinessBase<PageHits>
    {
        #region Business Properties and Methods

        //declare members
        private Guid _id = Guid.NewGuid();
        private Guid _pageid = Guid.NewGuid();
        private Guid _userid = Guid.NewGuid();
        private int _userrank = 0;
        private int _pagerevision = 0;
        private int _views = 0;
        private SmartDate _createdate = new SmartDate(DateTime.Now);

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid id
        {
            get
            {
                CanReadProperty("id", true);
                return _id;
            }
        }

        public Guid pageid
        {
            get
            {
                CanReadProperty("pageid", true);
                return _pageid;
            }
            set
            {
                CanWriteProperty("pageid", true);
                if (!_pageid.Equals(value))
                {
                    _pageid = value;
                    PropertyHasChanged("pageid");
                }
            }
        }

        public Guid userid
        {
            get
            {
                CanReadProperty("userid", true);
                return _userid;
            }
            set
            {
                CanWriteProperty("userid", true);
                if (!_userid.Equals(value))
                {
                    _userid = value;
                    PropertyHasChanged("userid");
                }
            }
        }

        public int userrank
        {
            get
            {
                CanReadProperty("userrank", true);
                return _userrank;
            }
            set
            {
                CanWriteProperty("userrank", true);
                if (!_userrank.Equals(value))
                {
                    _userrank = value;
                    PropertyHasChanged("userrank");
                }
            }
        }

        public int pagerevision
        {
            get
            {
                CanReadProperty("pagerevision", true);
                return _pagerevision;
            }
            set
            {
                CanWriteProperty("pagerevision", true);
                if (!_pagerevision.Equals(value))
                {
                    _pagerevision = value;
                    PropertyHasChanged("pagerevision");
                }
            }
        }

        public int views
        {
            get
            {
                CanReadProperty("views", true);
                return _views;
            }
            set
            {
                CanWriteProperty("views", true);
                if (!_views.Equals(value))
                {
                    _views = value;
                    PropertyHasChanged("views");
                }
            }
        }

        public DateTime createdate
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Date;
            }
        }

        public string createdateString
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Text;
            }
            set
            {
                CanWriteProperty("createdate", true);
                if (value == null)
                    value = string.Empty;
                if (!_createdate.Equals(value))
                {
                    _createdate.Text = value;
                    PropertyHasChanged("createdate");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _id;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // createdate
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "createdateString");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in PageHits
            //AuthorizationRules.AllowRead("id", "PageHitsReadGroup");
            //AuthorizationRules.AllowRead("pageid", "PageHitsReadGroup");
            //AuthorizationRules.AllowRead("userid", "PageHitsReadGroup");
            //AuthorizationRules.AllowRead("userrank", "PageHitsReadGroup");
            //AuthorizationRules.AllowRead("IvAccesstype", "PageHitsReadGroup");
            //AuthorizationRules.AllowRead("pagerevision", "PageHitsReadGroup");
            //AuthorizationRules.AllowRead("views", "PageHitsReadGroup");
            //AuthorizationRules.AllowRead("createdate", "PageHitsReadGroup");

            //AuthorizationRules.AllowWrite("userid", "PageHitsWriteGroup");
            //AuthorizationRules.AllowWrite("userrank", "PageHitsWriteGroup");
            //AuthorizationRules.AllowWrite("IvAccesstype", "PageHitsWriteGroup");
            //AuthorizationRules.AllowWrite("pagerevision", "PageHitsWriteGroup");
            //AuthorizationRules.AllowWrite("views", "PageHitsWriteGroup");
            //AuthorizationRules.AllowWrite("createdate", "PageHitsWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in PageHits
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PageHitsViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in PageHits
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PageHitsAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in PageHits
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PageHitsEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in PageHits
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("PageHitsDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private PageHits()
        { /* require use of factory method */
        }

        public static PageHits NewPageHits()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a PageHits");
            return DataPortal.Create<PageHits>();
        }

        public static PageHits GetPageHits(Guid id)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a PageHits");
            return DataPortal.Fetch<PageHits>(new Criteria(id));
        }

        public static void DeletePageHits(Guid id)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a PageHits");
            DataPortal.Delete(new Criteria(id));
        }

        public override PageHits Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a PageHits");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a PageHits");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a PageHits");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid id;

            public Criteria(Guid id)
            {
                this.id = id;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
         protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
            BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            //DAL.AddParameter("@pageid", criteria.pageid);

            using (SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader("usp_get_page_byid", CommandType.StoredProcedure, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _id = dr.GetGuid("id");
            _pageid = dr.GetGuid("pageid");
            _userid = dr.GetGuid("userid");
            _userrank = dr.GetInt32("userrank");
            _pagerevision = dr.GetInt32("pagerevision");
            _views = dr.GetInt32("views");
            _createdate = dr.GetSmartDate("createdate", _createdate.EmptyIsMin);
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
            BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery("usp_insert_page", CommandType.StoredProcedure, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            if (_userid != Guid.Empty)
                DAL.AddParameter("@userid", _userid);
            else
                DAL.AddParameter("@userid", DBNull.Value);
            DAL.AddParameter("@userrank", _userrank);
            DAL.AddParameter("@pagerevision", _pagerevision);
            DAL.AddParameter("@views", _views);
            DAL.AddParameter("@Newid", _id);
            //cm.Parameters["@Newid"].Direction = ParameterDirection.Output;
            DAL.AddParameter("@Newpageid", _pageid);
            //cm.Parameters["@Newpageid"].Direction = ParameterDirection.Output;
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        //protected override void DataPortal_Update()
        //{
        //    if (base.IsDirty)
        //    {
        //        ExecuteUpdate();
        //    }
        //}

        //private void ExecuteUpdate()
        //{
        //    BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        //    BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        //    DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

        //    AddUpdateParameters(ref DAL);

        //    DAL.ExecuteNonQuery("usp_update_page", CommandType.StoredProcedure, ConnectionState.Open);
        //}

        //private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        //{
        //    DAL.AddParameter("@id", _id);
        //    DAL.AddParameter("@pageid", _pageid);
        //    if (_userid != Guid.Empty)
        //        DAL.AddParameter("@userid", _userid);
        //    else
        //        DAL.AddParameter("@userid", DBNull.Value);
        //    DAL.AddParameter("@userrank", _userrank);
        //    DAL.AddParameter("@iv_accesstype", _ivAccesstype);
        //    DAL.AddParameter("@pagerevision", _pagerevision);
        //    DAL.AddParameter("@views", _views);
        //}

        //private void UpdateChildren(SqlConnection cn)
        //{
        //}
        #endregion //Data Access - Update

        #region Data Access - Delete
        //protected override void DataPortal_DeleteSelf()
        //{
        //    DataPortal_Delete(new Criteria(_id));
        //}

        //private void DataPortal_Delete(Criteria criteria)
        //{
        //    using (SqlConnection cn = new SqlConnection(Database.BlazeKBConnection))
        //    {
        //        cn.Open();

        //        ExecuteDelete(cn, criteria);

        //    }//using

        //}

        //private void ExecuteDelete(SqlConnection cn, Criteria criteria)
        //{
        //    using (SqlCommand cm = cn.CreateCommand())
        //    {
        //        cm.CommandType = CommandType.StoredProcedure;
        //        cm.CommandText = "DeletePageHits";

        //        cm.Parameters.AddWithValue("@id", criteria.id);

        //        cm.ExecuteNonQuery();
        //    }//using
        //}
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
